package com.example.demo.controller;

import com.example.demo.entity.JsonResult;
import com.example.demo.entity.Logs;
import com.example.demo.limit.RequestLimit;
import com.example.demo.mapper.CustomerMapper;
import com.example.demo.util.HuihepaySubmit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/transfaner")
@Transactional
public class Topay {
	@Autowired
	CustomerMapper customerMapper;

	Logs logs = new Logs();
	/**localhost:6080/transfaner/Topay?phone=18712882023&amount=0.01
	 * 生成付款的二维码
	 * @param amount
	 * @param phone
	 * @return
	 * @throws Exception
	 */
	@RequestLimit(count=10,time=5000)
	@PostMapping("Topay")
	public JsonResult Topay(double amount,String phone) throws Exception {
		JsonResult json = new JsonResult();
		Date date = new Date();
		Map<String,String> map = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmss");
		//把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		String str = "VIP";
		String urlString = URLEncoder.encode(str, "UTF-8");
		sParaTemp.put("AppId", "201709100001184369"); //应用ID，等同于商户编号
		sParaTemp.put("Body", str);
		sParaTemp.put("Charset", "UTF-8");
		sParaTemp.put("Format", "JSON");
		sParaTemp.put("Method", "trade.page.pay");
		sParaTemp.put("NotifyUrl", "http://1833g1872k.imwork.net/transfaner/nofity");
//		sParaTemp.put("NotifyUrl", "http://www.zhulipingtai.com/earn/transfaner/nofity");

		sParaTemp.put("OutTradeNo", "PH"+phone+sd.format(date));
		sParaTemp.put("PayType", "2");
		sParaTemp.put("Subject", urlString);
		sParaTemp.put("Timestamp", sdf.format(date)); // 请求时间 格式 yyyy-MM-dd HH:mm:ss
		sParaTemp.put("TotalAmount", String.valueOf(1));
		sParaTemp.put("Version", "1.0");
//		sParaTemp.put("Version", "1.0");
		//建立请求
		HuihepaySubmit huihepaySubmit = new HuihepaySubmit();
		String sHtmlText = huihepaySubmit.buildRequest(sParaTemp);
		String[] s = sHtmlText.split("\"");
		logs.setLogsCode(sParaTemp.get("OutTradeNo"));
		logs.setLogsTime(sd.format(date));
		logs.setPhone(phone);
		logs.setLogsContent(str);
		Double d = Double.parseDouble(String.valueOf(amount*100));
		Integer m = d.intValue();
		logs.setAmount(m);
		logs.setLogsType("2");
		customerMapper.saveLogs(logs);
		map.put("code",s[3]);
		json.setData(map);
//		json.setData(s[3]);
		json.setSuccess(true);
		return json;
	}

	/**
	 * 接收支付返回的异步信息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@PostMapping("nofity")
	public String nofity(HttpServletRequest request, HttpServletResponse response)
			throws Exception{
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("Code",request.getParameter("Code"));
		String s = request.getParameter("OutTradeNo");
		if(sParaTemp.get("Code").equals("0")){
			logs.setIsSure(1);
			SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			logs.setTimeSure(sd.format(new Date()));
			logs.setLogsCode(s);
			logs.setFalseBack("支付成功！！！！");
			customerMapper.updateLogs(logs);
			//todo 如果付款成功 则改变会员
			String b = s.substring(2,13);//获取用户手机号码，根据手机号码更改会员状态
			customerMapper.updateMemberState(b);
			//但会员认证成功以后，会给一级，二级，三级好友钱包中分别放入60,30,10元
			//首先查询一二三级好友
			String friends1 = customerMapper.getFriends1(b);
			String friends2 = customerMapper.getFriends2(b);
			String friends3 = customerMapper.getFriends3(b);
			//将奖励的好友的钱放入钱包
			if(friends1!=null){
				customerMapper.saveWalletMoney(6000,friends1);
				String startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				customerMapper.saveInvitationLogs(startTime,6000,friends1);
				if(friends2!=null){
					customerMapper.saveWalletMoney(3000,friends2);
					customerMapper.saveInvitationLogs(startTime,3000,friends2);
					if(friends3!=null){
						customerMapper.saveWalletMoney(1000,friends3);
						customerMapper.saveInvitationLogs(startTime,1000,friends3);
					}
				}
			}
		}
		return "SUCCESS";
	}
}

/*
	SELECT CASE WHEN currentPeople IS NULL THEN '0' ELSE currentPeople END AS currentPeople,needPeople,stLevel,enLevel
		FROM(
		SELECT A.friends_first-stPeople AS currentPeople, enPeople-stPeople AS needPeople ,stLevel,enLevel
		FROM (
		SELECT  A.friends_first , wa.`member_level` AS stLevel,le.people AS stPeople,lev.`level` AS enLevel,lev.`people` AS enPeople
		FROM wallet wa
		INNER JOIN LEVEL le ON le.`level` = wa.`member_level`
		INNER JOIN LEVEL lev ON lev.`level` = wa.`member_level`+1
		LEFT JOIN (
		SELECT COUNT(*) AS friends_first,inviter
		FROM customer
		WHERE inviter = '666666' AND member=1
		)A ON A.inviter = wa.invitation_code
		WHERE wa.invitation_code = '666666'
		)A
		)A*/
